<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        center
      >
      </el-alert>

      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 添加表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
      >
        <!-- tab栏区域 -->
        <el-tabs
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="clickTab"
          v-model="activeIndex"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息表单区域 -->

            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>

            <!-- 级联选择框，选择商品分类 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="options"
                :props="cascaderProps"
                @change="changeCategories"
                filterable
                clearable
                ref="cascaderRef"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数区域 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性区域 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片区域 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示要上传到的后台API地址 -->
            <!-- headers 上传图片没有发生axios请求，所有请求头部中没有携带token，因此要自己手动添加请求头 -->
            <!-- on-success上传成功会调用的钩子函数 -->
            <!-- on-remove删除照片会调用的钩子函数 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容区域 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button class="mtop" type="primary" @click="submitAddGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片弹框 -->
    <el-dialog
      :visible.sync="previewDialog"
      title="图片预览"
      width="50%"
      @close="closeAddParamsDialog"
    >
      <img :src="previewImg" style="width:100%;" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      //添加商品表单参数
      addForm: {
        goods_name: '',
        //商品所属的分类数组
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        //上传的图片临时路径（对象）
        pics: [],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      //添加商品验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '商品名称长度为1~200个字符',
            trigger: 'blur'
          }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //分类列表下拉选择参数
      options: [],
      //级联选择器数据的定义
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //选中分类的id
      cateId: '',
      //控制步骤条的激活状态
      //控制选项卡的选中名称,二者共用一个属性就可以产生联动效果
      activeIndex: '0',
      //存储动态参数的数据
      manyTableData: [],
      //存储静态属性的数据
      onlyTableData: [],
      //上传图片的根路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      //上传图片的headers请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //控制图片预览
      previewDialog: false,
      //预览图片的路径
      previewImg: ''
    }
  },
  created() {
    this.getCateGoriesData()
  },
  methods: {
    //获取分类参数
    async getCateGoriesData() {
      const res = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //获取成功把返回的数据赋给options
      this.options = res.data
    },
    //监听级联选择框的变化事件
    changeCategories() {
      //只允许选中三级分类
      if (this.addForm.goods_cat.length <= 2) {
        this.addForm.goods_cat = []
        return
      }
      //存储选中的分类的id
      this.cateId = this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    },
    //如果用户没有选择商品分类阻止切换tab
    beforeTabLeave(activeName, oldActiveName) {
      // console.log('即将要离开的tab' + oldActiveName)
      // console.log('即将要离进入的tab' + activeName)
      //
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //监听tab切换事件
    async clickTab() {
      // console.log(this.activeIndex)
      //判断点击了哪个tab，来发起响应的请求
      if (this.activeIndex === '1') {
        //证明点击了商品参数
        this.getParamsData('many')
      } else if (this.activeIndex === '2') {
        //证明点击了商品属性
        this.getParamsData('only')
      }
    },
    //获取动态参数或静态属性的函数
    async getParamsData(sel) {
      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //获取成功

      if (sel === 'many') {
        //对得到的数据作进一步处理
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    //上传成功会调用的函数，接收返回的参数
    handleSuccess(response) {
      // console.log(response)
      //接收返回参数的图片的零时地址
      const pic_path = { pic: response.data.tmp_path }
      // console.log(pic_path)
      //把这个零时地址存储在addForm的pic数组中
      this.addForm.pics.push(pic_path)
      console.log(this.addForm)
    },
    //删除图片会调用函数，
    handleRemove(file) {
      // console.log(file)
      //1.获取要删除图片的零时路径
      const filePath = file.response.data.tmp_path
      //2.从pic数组中找到对应要删除图片的索引
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      //根据index利用splice删除pics中对应的图片路径
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm)
    },
    //预览图片钩子函数
    handlePreview(file) {
      console.log(file)
      this.previewDialog = true
      this.previewImg = file.response.data.url
    },
    //监听图片预览弹框的关闭事件
    closeAddParamsDialog() {
      //清空内容
      this.previewImg = ''
    },
    //点击提交商品按钮进行商品添加
    submitAddGoods() {
      //预校验表单
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          //校验失败
          this.$message.error('请确认所有选项都已填写！')
        }
        //校验通过
        //修改一下goods_cat的格式，后台接收的是一个以逗号分隔的字符串
        //深拷贝addForm因为级联选择框绑定的goods_cat要求是一个数组
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        //处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(newInfo)
        })
        //处理静态参数
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          form.attrs.push(newInfo)
        })
        console.log(this.addForm)
        console.log(form)
        //发起axios请求
        const res = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        //添加成功
        this.$message.success(res.meta.msg)
        //跳转到商品列表
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scpoed>
.el-steps {
  margin-top: 18px;
}
.el-tabs {
  margin-top: 60px;
}
.el-checkbox {
  margin: 8px !important;
}
.mtop {
  margin-top: 15px !important;
}
</style>